package nkw;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import robocode.BattleResults;
import robocode.control.events.BattleCompletedEvent;
import robocode.control.events.TurnEndedEvent;
import robocode.control.snapshot.IRobotSnapshot;
import robocode.control.snapshot.ITurnSnapshot;
import robocode.control.testing.RobotTestBed;

/**
 * Tests that CompetitiveRobot changes gun direction immediately after onHitRobot.
 * 
 * @author Noah Woodden
 * 
 */
public class TestBehaviorOne extends RobotTestBed {
  boolean hitRobot = false;
  double hitRobotDirection;
  boolean turnedAfterHitRobot = true;
  int turnsElapsed = 0;

  /**
   * Specifies that Crazy and Robot are to be matched up in this test case.
   * 
   * @return The comma-delimited list of robots in this match.
   */
  @Override
  public String getRobotNames() {
    return "sample.Crazy,nkw.CompetitiveRobot";
  }

  /**
   * After each turn, check to see if we're at a corner. If so, set the corresponding flag.
   * 
   * @param event Info about the current state of the battle.
   */
  @Override
  public void onTurnEnded(TurnEndedEvent event) {
    ITurnSnapshot turn = event.getTurnSnapshot();
    IRobotSnapshot robot = turn.getRobots()[1];

    if (robot.getState().isHitRobot()) {
      System.out.println("hit other robot");
      this.hitRobot = true;
      this.hitRobotDirection = robot.getGunHeading();
    }
    // Check to see if the robot's gun turned
    if (this.hitRobot) {
      // Robot gun direction has changed
      if (this.hitRobotDirection == robot.getGunHeading()) {
        if (this.turnsElapsed < 2) {
          this.turnsElapsed++;
        }
        else {
          System.out.println("did not turn after robot hit");
          this.turnedAfterHitRobot = false;
          this.turnsElapsed = 0;
          this.hitRobot = false;
        }
      }
      else {
        System.out.println("turned after robot hit");
        this.hitRobot = false;
        this.turnsElapsed = 0;
      }
    }
  }

  /**
   * After the battle, check to see that we've visited the corners.
   * 
   * @param event Details about the completed battle.
   */
  @Override
  public void onBattleCompleted(BattleCompletedEvent event) {
    // Return the results in order of getRobotNames.
    BattleResults[] battleResults = event.getIndexedResults();
    // Sanity check that results[1] is CompetitiveRobot (not strictly necessary, but illustrative).
    BattleResults botResults = battleResults[1];
    String robotName = botResults.getTeamLeaderName();
    assertEquals("Check that results[1] is CompetitiveRobot", robotName, "nkw.CompetitiveRobot*");

    assertTrue("Robot did not turn gun after all wall hits", this.turnedAfterHitRobot);
  }

  /**
   * This test runs for 10 rounds.
   * 
   * @return The number of rounds.
   */
  @Override
  public int getNumRounds() {
    return 10;
  }
}
